<template>
  <view class="user-list-container">
    <view class="header-section">
      <text class="page-title">用户管理</text>
    </view>
    
    <view class="filter-section">
      <view class="filter-item">
        <input class="filter-input" placeholder="搜索用户名/邮箱/手机号" v-model="searchKeyword" />
      </view>
      <view class="filter-item">
        <picker mode="selector" :range="roleOptions" @change="onRoleChange">
          <view class="filter-input">{{ selectedRole || '角色筛选' }}</view>
        </picker>
      </view>
      <view class="filter-item">
        <picker mode="selector" :range="statusOptions" @change="onStatusChange">
          <view class="filter-input">{{ selectedStatus || '状态筛选' }}</view>
        </picker>
      </view>
      <button class="filter-button" @click="searchUsers">搜索</button>
    </view>
    
    <view class="user-list">
      <view class="user-item" v-for="user in userList" :key="user.id">
        <view class="user-info">
          <text class="user-name">{{ user.username }}</text>
          <text class="user-email">{{ user.email }}</text>
          <text class="user-phone">{{ user.phone }}</text>
        </view>
        <view class="user-role">
          <text class="role-tag" :class="getRoleClass(user.role)">{{ user.role }}</text>
        </view>
        <view class="user-status">
          <text class="status-tag" :class="getStatusClass(user.status)">{{ user.status === 1 ? '启用' : '禁用' }}</text>
        </view>
        <view class="user-actions">
          <button class="action-button" @click="editUser(user.id)">编辑</button>
          <button class="action-button" :class="user.status === 1 ? 'danger' : 'success'" @click="toggleUserStatus(user)">
            {{ user.status === 1 ? '禁用' : '启用' }}
          </button>
        </view>
      </view>
    </view>
    
    <view class="pagination-section">
      <button class="pagination-button" :disabled="currentPage <= 1" @click="prevPage">上一页</button>
      <text class="page-info">第 {{ currentPage }} 页，共 {{ totalPages }} 页</text>
      <button class="pagination-button" :disabled="currentPage >= totalPages" @click="nextPage">下一页</button>
    </view>
    
    <view class="empty-state" v-if="userList.length === 0">
      <text class="empty-text">暂无用户数据</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { userApi } from '../../../src/services/system'

// 定义用户类型
interface User {
  id: number
  username: string
  email: string
  phone: string
  role: string
  status: number
}

// 搜索关键词
const searchKeyword = ref('')

// 角色筛选选项
const roleOptions = ['全部', 'admin', 'coach', 'member']
const selectedRole = ref('')

// 状态筛选选项
const statusOptions = ['全部', '启用', '禁用']
const selectedStatus = ref('')

// 分页信息
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(1)
const totalUsers = ref(0)

// 用户列表
const userList = ref<User[]>([])

// 页面加载时获取用户列表
onMounted(() => {
  fetchUserList()
})

// 获取用户列表
const fetchUserList = async () => {
  try {
    const params: any = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value
    }
    
    if (selectedRole.value && selectedRole.value !== '全部') {
      params.role = selectedRole.value
    }
    
    if (selectedStatus.value && selectedStatus.value !== '全部') {
      params.status = selectedStatus.value === '启用' ? 1 : 0
    }
    
    const response: any = await userApi.getUserList(params)
    userList.value = response.data.list || response.data
    totalUsers.value = response.data.total || userList.value.length
    totalPages.value = Math.ceil(totalUsers.value / pageSize.value)
    
    uni.showToast({
      title: '获取用户列表成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('获取用户列表失败:', error)
    uni.showToast({
      title: '获取用户列表失败',
      icon: 'none'
    })
  }
}

// 角色筛选变化
const onRoleChange = (e: any) => {
  selectedRole.value = roleOptions[e.detail.value]
}

// 状态筛选变化
const onStatusChange = (e: any) => {
  selectedStatus.value = statusOptions[e.detail.value]
}

// 搜索用户
const searchUsers = () => {
  currentPage.value = 1
  fetchUserList()
}

// 编辑用户
const editUser = (userId: number) => {
  uni.navigateTo({
    url: `/pages/system/user/edit?id=${userId}`
  })
}

// 切换用户状态
const toggleUserStatus = async (user: User) => {
  try {
    await userApi.updateUserStatus(user.id, { status: user.status === 1 ? 0 : 1 })
    
    // 更新本地状态
    user.status = user.status === 1 ? 0 : 1
    
    uni.showToast({
      title: `${user.status === 1 ? '启用' : '禁用'}用户成功`,
      icon: 'success'
    })
    
    // 重新获取用户列表
    fetchUserList()
  } catch (error) {
    console.error('更新用户状态失败:', error)
    uni.showToast({
      title: '更新用户状态失败',
      icon: 'none'
    })
  }
}

// 获取角色样式类
const getRoleClass = (role: string) => {
  switch (role) {
    case 'admin': return 'role-admin'
    case 'coach': return 'role-coach'
    case 'member': return 'role-member'
    default: return ''
  }
}

// 获取状态样式类
const getStatusClass = (status: number) => {
  return status === 1 ? 'status-active' : 'status-inactive'
}

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchUserList()
  }
}

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    fetchUserList()
  }
}
</script>

<style lang="scss" scoped>
.user-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.header-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  
  .page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
  }
}

.filter-section {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  align-items: center;
}

.filter-item {
  flex: 1;
  min-width: 150rpx;
}

.filter-input {
  background-color: #f5f5f5;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.filter-button {
  background-color: #4B0082;
  color: #fff;
  border: none;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.user-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.user-item {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.user-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.user-email, .user-phone {
  font-size: 28rpx;
  color: #666;
}

.user-role, .user-status {
  display: flex;
  align-items: center;
}

.role-tag, .status-tag {
  padding: 5rpx 15rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.role-admin {
  background-color: #ffebee;
  color: #f44336;
}

.role-coach {
  background-color: #e8f5e9;
  color: #4caf50;
}

.role-member {
  background-color: #e3f2fd;
  color: #2196f3;
}

.status-active {
  background-color: #e8f5e9;
  color: #4caf50;
}

.status-inactive {
  background-color: #ffebee;
  color: #f44336;
}

.user-actions {
  display: flex;
  gap: 20rpx;
}

.action-button {
  flex: 1;
  background-color: #4B0082;
  color: #fff;
  border: none;
  padding: 10rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.action-button.danger {
  background-color: #f44336;
}

.action-button.success {
  background-color: #4caf50;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30rpx;
  padding: 0 20rpx;
}

.pagination-button {
  background-color: #4B0082;
  color: #fff;
  border: none;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.pagination-button[disabled] {
  background-color: #ccc;
}

.page-info {
  font-size: 28rpx;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>